package service

import (
	"errors"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	ms "go-admin/internal/model/api/model_response"
	"go-admin/pkg/errcode"
)

func (s *Service) CreateDept(param *mr.CreateDeptRequest) (string, error) {
	// 根据字典名称和字典type是否重复
	dept, err := s.dao.GetDeptByDeptName(param.DeptName)
	if err != nil {
		return dept.Id, err
	}
	// 判断部门是否存在
	if dept.Id != "" {
		return dept.Id, errors.New("部门已存在")
	}
	insertId, err := s.dao.CreateDept(param)
	if err != nil {
		return "", errcode.ErrorCreateDictFail
	}
	return insertId, nil
}

func (s *Service) UpdateDept(param *mr.UpdateDeptRequest) error {
	return s.dao.UpdateDept(param)
}

func (s *Service) DeleteDept(id string) error {
	return s.dao.DeleteDept(id)
}

//
func (s *Service) GetDeptListAll() ([]*model.Dept, error) {
	return s.dao.GetDeptListAll()
}

// 获取部门tree
func (s *Service) GetDeptTree() ([]*ms.ListDeptResponse, error) {
	// 获取所有的部门
	deptListAll, err := s.GetDeptListAll()
	if err != nil {
		return nil, err
	}
	resTree := ms.ModelToListDeptTreeRes(deptListAll)
	// 将parentId为 '0' 的装进去
	list := make([]*ms.ListDeptResponse, 0)
	for _, r := range resTree {
		if r.ParentId != "0" {
			continue
		}
		list = append(list, coverTree(resTree, r))
	}
	return list, nil
}

func (s *Service) GetDeptById(id string) (*model.Dept, error) {
	dept, err := s.dao.GetDeptById(id)
	if err != nil {
		return nil, err
	}
	// 判断是否存在
	if dept.Id == "" {
		return nil, err
	}
	return dept, nil
}

func coverTree(list []*ms.ListDeptResponse, l *ms.ListDeptResponse) *ms.ListDeptResponse {
	// 存放找到的节点
	min := make([]*ms.ListDeptResponse, 0)
	for _, ls := range list {
		if l.Id != ls.ParentId {
			continue
		}
		mi := ms.ListDeptResponse{}
		mi.Id = ls.Id
		mi.ParentId = ls.ParentId
		mi.CreatedOn = ls.CreatedOn
		mi.IsBanned = ls.IsBanned
		mi.Sort = ls.Sort
		mi.DeptName = ls.DeptName
		mi.Children = []*ms.ListDeptResponse{}
		ms := coverTree(list, &mi)
		min = append(min, ms)
	}
	l.Children = min
	return l
}
